﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using PMS.BusinessFacade;
using PMS.EntityManage;
using PMS.Common;
using PMS.EntityQuery;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using BusinessFacade;
using EntityManage;

public partial class Modules_System_Org_Tree_Ajax : System.Web.UI.Page
{

    ISys_UserHandler userHandler = new Sys_UserManage();
    ISys_UserHandlerExt userExtHandler = new Sys_UserManageExt();
    ISys_OrganizationHandler orgHandler = new Sys_OrganizationManage();
    ISys_OrganizationHandlerExt orgExtHandler = new Sys_OrganizationManageExt();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string getTree = Request.QueryString["getTree"];
            string method = Request.QueryString["method"];
            if (getTree != null && !"".Equals(getTree))
            {
                // 读取树
                int pid = 0;
                StringBuilder head = new StringBuilder();
                List<Sys_OrganizationQuery> dpmList = new List<Sys_OrganizationQuery>();

                string ppid = Request.QueryString["ppid"];
                if (ppid == null || "".Equals(ppid))
                {
                    Sys_OrganizationQuery root = orgExtHandler.GetRootOrganization();
                    dpmList.Add(root);
                    pid = root.ID;
                }
                else
                {
                    pid = int.Parse(ppid);
                }
                List<Sys_OrganizationQuery> t = (List<Sys_OrganizationQuery>)orgExtHandler.GetChildByParentID(pid);
                dpmList.AddRange(t);

                if (dpmList != null)
                {
                    head.Append("[{\"dpmt\":[");
					foreach(Sys_OrganizationQuery dpmt in dpmList)
					{
						head.Append("{");
						head.Append("\"id\":\"" + dpmt.ID);
						head.Append("\",\"parentId\":\"" + dpmt.Parent_ID);
						head.Append("\",\"name\":\"" + dpmt.Name);
                        head.Append("\",\"type\":\"" + dpmt.Type);
                        head.Append("\",\"status\":\"" + dpmt.Status);
                        head.Append("\",\"code\":\"" + dpmt.Code);
						head.Append("\",\"isLeaf\":" + (dpmt.Type == 0 ? "true" : "false"));
						head.Append("},");
					}
					if (dpmList.Count > 0) {
                        head = head.Remove(head.Length - 1, 1);
					}
					head.Append("]}]");
                }

                Response.ContentType = "text/html";
                Response.ContentEncoding = Encoding.UTF8;
                Response.Write(head.ToString());
            }
            else if ("save".Equals(method.ToLower()))
            {
                string id = Request.Form["id"];
                string pid = Request.Form["pid"];
                string code = Request.Form["code"];
                string name = Request.Form["name"];
                int status = int.Parse(Request.Form["status"]);
                int type = int.Parse(Request.Form["type"]);

                // 判断权限
                if (Session["UserPurviews"] != null)
                {
                    string strPur = Session["UserPurviews"].ToString();
                    if (id == null || "".Equals(id.Trim()))
                    {
                        if (!strPur.Contains("202011"))
                        {
                            Response.Redirect("~/Login.aspx");
                        }
                    }
                    else
                    {
                        if (!strPur.Contains("202012"))
                        {
                            Response.Redirect("~/Login.aspx");
                        }
                    }
                }
                else
                {
                    Response.Redirect("~/Login.aspx");
                }

                Sys_OrganizationQuery query = new Sys_OrganizationQuery();
                if (id != null && !"".Equals(id.Trim()))
                {
                    query.ID = int.Parse(id);

                    Sys_OrganizationQuery org = orgHandler.GetSys_OrganizationQuery(query.ID);
                    if (!org.Code.Equals(code))
                    {
                        // 判断Code是否已存在
                        Sys_OrganizationQuery[] exists = orgHandler.GetSys_OrganizationQueryList(" Code=@Code", new SqlParameter[1] { new SqlParameter("@Code", code) });
                        if (exists.Length > 0)
                        {
                            Response.ContentType = "text/html";
                            Response.ContentEncoding = Encoding.UTF8;
                            Response.Write("[{\"resultCode\":1,\"errMsg\":\"代码已存在！\"}]");
                            return;
                        }
                    }
                }
                else
                {
                    // 判断Code是否已存在
                    Sys_OrganizationQuery[] exists = orgHandler.GetSys_OrganizationQueryList(" Code=@Code", new SqlParameter[1] { new SqlParameter("@Code", code) });
                    if (exists != null && exists.Length > 0)
                    {
                        Response.ContentType = "text/html";
                        Response.ContentEncoding = Encoding.UTF8;
                        Response.Write("[{\"resultCode\":1,\"errMsg\":\"代码已存在！\"}]");
                        return;
                    }
                }
                if (pid != null && !"".Equals(pid.Trim()) && !"0".Equals(pid.Trim()))
                {
                    query.Parent_ID = int.Parse(pid);
                }
                query.Code = code;
                query.Name = name;
                query.Status = status;
                query.Type = type;
                string uid = Session["CurrentUserID"].ToString();
                query.Sys_User_ID = int.Parse(uid);

                try
                {
                    if (id == null || "".Equals(id.Trim())) {
                        int newId = 0;
                        orgHandler.InsertSys_Organization(query, ref newId);
                        query.ID = newId;
                    }else {
                        orgHandler.UpdateSys_Organization(query);
                    }
                }
                catch (Exception ex)
                {
                    Response.ContentType = "text/html";
                    Response.ContentEncoding = Encoding.UTF8;
                    Response.Write("[{\"resultCode\":1,\"errMsg\":\"未知错误！\"}]");
                    return;
                }

                Response.ContentType = "text/html";
                Response.ContentEncoding = Encoding.UTF8;
                Response.Write("[{\"resultCode\":0,\"id\":" + query.ID + "}]");
                return;
            }
            else if ("del".Equals(method.ToLower()))
            {
                // 判断权限
                if (Session["UserPurviews"] != null)
                {
                    string strPur = Session["UserPurviews"].ToString();
                    if (!strPur.Contains("202013"))
                    {
                        Response.Redirect("~/Login.aspx");
                    }
                }
                else
                {
                    Response.Redirect("~/Login.aspx");
                }
                string id = Request.Form["id"];
                try
                {
                    Sys_OrganizationQuery query = orgHandler.GetSys_OrganizationQuery(int.Parse(id));
                    List<Sys_OrganizationQuery> childs = orgExtHandler.GetChildByParentID(query.ID);
                    if (childs.Count > 0)
                    {
                        Response.ContentType = "text/html";
                        Response.ContentEncoding = Encoding.UTF8;
                        Response.Write("[{\"resultCode\":1,\"errMsg\":\"该部门还有下级部门，不能删除！\"}]");
                        return;
                    }
                    // 判断是否有用户属于该部门
                    DataTable dt = userExtHandler.GetUsersByOrgID(query.ID);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        Response.ContentType = "text/html";
                        Response.ContentEncoding = Encoding.UTF8;
                        Response.Write("[{\"resultCode\":1,\"errMsg\":\"该部门还有用户，不能删除！\"}]");
                        return;
                    }

                    orgHandler.DeleteSys_Organization(query.ID);

                    Response.ContentType = "text/html";
                    Response.ContentEncoding = Encoding.UTF8;
                    Response.Write("[{\"resultCode\":0}]");
                    return;
                }
                catch (Exception ex)
                {
                    Response.ContentType = "text/html";
                    Response.ContentEncoding = Encoding.UTF8;
                    Response.Write("[{\"resultCode\":1,\"errMsg\":\"未知错误！\"}]");
                    return;
                }
            }
        }
    }
}
